<?php
namespace app\console\controller;
use app\model\CompanyWithdraw as SelfModel;
use app\model\LeasingCompany;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\facade\Route;
use think\facade\View;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Cookie;
class CompanyWithdraw extends Base
{



    public function initialize()
    {
        parent::initialize();
        $this->model = "\app\model\CompanyWithdraw";
        $this->list_rows = 20;
        
    }
    public function select()
    {
            $leasing_company = LeasingCompany::order([ 'id' => 'desc'])->select()->toArray();
            View::assign('leasing_company', $leasing_company);

    }

    public function update()
    {
        $param = $this->request->param();
        Db::starttrans();
        $info = (new $this->model)->lock(true)->find($param['id']);
        if ($this->request->isPost()) {

            try {

                $ret = $info->save($param);
                if($ret === false){
                    fail('修改失败');
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                fail('修改失败');
            }
            win('修改成功', Route::buildUrl('index'));
        }


        $this->select();
        return View::fetch('create', ['info' => $info]);
    }


    public function audit_status()
    {

        Db::startTrans();
        try {
            $param = Request::param();
            $company_withdraw = $this->model::where('id', $param['id'])->find();
            $leasing_company = LeasingCompany::where('id', $company_withdraw['company_id'])->find();
            if ($leasing_company['balance'] < $company_withdraw['price']) {
                return json(['code' => 400, 'msg' => '账户余额不足,余额:' . $leasing_company['balance']]);
            }
            if ($company_withdraw['audit_status'] !== 1) {
                return json(['code' => 400, 'msg' => '状态不对']);
            }
            if ($company_withdraw['audit_status'] == 1) {
                $ret = $this->model::where('id', $param['id'])->where('audit_status', 1)->update(['audit_status' => 2]);
                LeasingCompany::where('id', $company_withdraw['company_id'])->dec('balance',$company_withdraw['price'])->update();
                if ($ret) {
                    Db::commit();
                    return json(['code' => 200, 'msg' => '审核成功']);
                }
            }
            return json(['code' => 400, 'msg' => '失败']);
        }  catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }





}